<?php
global $DBobject;
$data = [];
if (!empty($_REQUEST['query'])) {
    if ($_REQUEST['query']%10000==0) {
        $enum = $_REQUEST['query']+10000;
    } elseif ($_REQUEST['query']%100==0) {
        $enum = $_REQUEST['query']+100;
    }
    $sql ='SELECT region_id AS `value`,region_name AS `text` FROM tbl_region WHERE region_id > :snum AND region_id < :enum';
    //var_dump($sql);
    $params = array('snum'=>$_REQUEST['query'],'enum'=> $enum);
    $res = $DBobject->wrappedSql($sql, $params);
    $city = [];
    $area = [];
    foreach ($res as $r) {
        if ($r['value']%100==0) {
            $city[] = $r;
        } else {
            $area[] = $r;
        }
    }
    $data = !empty($city) ? $city : $area;
}
if (!empty($_REQUEST['state'])) {
    $sql = 'SELECT region_id FROM tbl_region WHERE region_name = :rname AND region_id mod 10000 = 0 LIMIT 1';
    $params = array('rname'=>$_REQUEST['state']);
    $res = $DBobject->wrappedSql($sql, $params);
    //var_dump($res[0]['region_id']);exit;
    
    $sql ='SELECT region_id AS `value`,region_name AS `text` FROM tbl_region WHERE region_id > :snum AND region_id < :enum AND region_id mod 100 = 0';
    //var_dump($sql);
    $params = array('snum'=>$res[0]['region_id'],'enum'=> $res[0]['region_id']+10000);
    $res = $DBobject->wrappedSql($sql, $params);
    if (is_array($res)) {
        $data = $res;
    }
}
if (!empty($_REQUEST['name']) && !empty($_REQUEST['type'])) {
    $type = $_REQUEST['type'];
    $sql = 'SELECT region_id FROM tbl_region WHERE region_name = :rname ';
    if ($type == 'suburb') {
        $sql .= ' AND region_id mod 10000 = 0';
    } else {
        $sql .= ' AND region_id mod 10000 > 0 AND region_id mod 100 = 0';
    }
    $params = array('rname'=>$_REQUEST['name']);
    $res = $DBobject->wrappedSql($sql, $params);
    //var_dump($res[0]['region_id']);exit;
    
    $sql ='SELECT region_name AS `value`,region_name AS `text` FROM tbl_region WHERE region_id > :snum AND region_id < :enum';
    //var_dump($sql);
    if ($type == 'suburb') {
        $sql .= ' AND region_id mod 100 = 0';
    } else {
        $sql .= ' AND region_id mod 100 > 0';
    }
    $params = array('snum'=>$res[0]['region_id'],'enum'=> $res[0]['region_id']+ ($type=='suburb'?10000:100));
    $res = $DBobject->wrappedSql($sql, $params);
    if (is_array($res)) {
        array_unshift($res, ['value'=>'','text'=>'请选择']);
        $data = $res;
    }
}
echo json_encode($data);
die();
